<template>
  <common-page :title="title">
    <el-button slot="header" @click="goBack">返回</el-button>
    <traceabilityReport
      v-if="openReport"
      @traceabilityTaskReport="traceabilityTaskReport"
      :uri="logquery"
      :eventDetails="eventDetails"
      :accountIp="accountIp"
      :interfacePortrait="interfacePortrait"
    >
    </traceabilityReport>
    <div class="execution-history-overview-wrap" slot="content" v-else>
      <div class="grid-column-4">
        <icon-kpi :config="kpi_1"></icon-kpi>
        <icon-kpi :config="kpi_2"></icon-kpi>
        <icon-kpi :config="kpi_3"></icon-kpi>
        <icon-kpi :config="kpi_4"></icon-kpi>
      </div>
      <div class="column-divided"></div>
      <div class="grid-column-1">
        <div class="chart-container">
          <title-chart
            type="table"
            title="反演结果路径图"
          >
            <JsPlumb :formData="formData"></JsPlumb>
          </title-chart>
        </div>
      </div>
      <div class="column-divided"></div>
      <div class="grid-column-1">
        <div class="chart-container">
          <title-chart
            type="table"
            title="风险因子溯源分析"
          >
            <div class="chart-table">
              <el-table
                height="100%"
                :stripe="true"
                :data="columnOption2"
              >
                <el-table-column
                  label="线索字段"
                  align="left"
                  prop="senstiveName"
                  show-overflow-tooltip/>
                <el-table-column
                  label="URL"
                  align="left"
                  prop="apiUrl"
                  show-overflow-tooltip/>
                <el-table-column
                  label="源IP"
                  align="left"
                  prop="address"
                  show-overflow-tooltip/>

              </el-table>
            </div>
          </title-chart>
        </div>
      </div>
      <div class="column-divided"></div>
      <div class="grid-column-2">
        <div class="chart-container">
          <title-chart
            type="chart-line"
            title="近7天访问量趋势"
            :dataset="columnOption3"
          ></title-chart>
        </div>
        <div class="chart-container">
          <title-chart
            type="chart-pie"
            title="近7天命中接口"
            :dataset="columnOption4"
            @chartClick="pieClick"
          ></title-chart>
        </div>
      </div>
    </div>
  </common-page>

</template>

<script>
  import {
    traceReport
  } from '@/api/traceabilityTask'
  import IconKpi from '@/components/IconKpi'
  import TitleChart from '@/components/EChart/TitleChart'
  import traceabilityReport from '../traceabilityReport'
  import JsPlumb from '@/components/JsPlumb/index'
  import { parseTime } from '@/utils/ruoyi'

  export default {
    name: 'index',
    components: {
      IconKpi,
      TitleChart,
      traceabilityReport,
      JsPlumb
    },
    props: {
      id: {
        type: [Number, String]
      },
      data: {
        type: Object,
        default: null,
      },
    },
    data() {
      return {
        title: '',
        formData: null,
        kpi_1: {
          icon: 'iconfont icon-database',
          color: '#e69138',
          label: '溯源总数据量',
          value: 0
        },
        kpi_2: {
          icon: 'iconfont icon-kuyonghuzongshu',
          color: '#72c140',
          label: '溯源上行总量',
          value: 0,
          suffix: 'kb'
        },
        kpi_3: {
          icon: 'iconfont icon-chart',
          color: '#e13c39',
          label: '溯源下行总量',
          value: '0',
          suffix: 'kb'
        },
        kpi_4: {
          icon: 'iconfont icon-minganbiaozongshu',
          color: '#448ef7',
          label: '溯源线索数据量',
          value: '0'
        },
        columnOption2: [],
        columnOption3: {
          dimensions: ['name', 'value'],
          source: [],
          option: {
            xAxis: {
              type: 'category'
            },
            yAxis: {
              name: '单位:次',
              type: 'value'
            },
            series: [
              {
                type: 'line',
                smooth: true
              }
            ]

          }
        },
        columnOption4: {
          dimensions: ['name', 'value'],
          source: [],
          option: {
            xAxis: {
              type: 'category'
            },
            yAxis: {
              type: 'value'
            },
            series: [
              {
                type: 'pie'
              }

            ]
          }
        },
        openReport: false,
        logquery: null,
        eventDetails: {},
        accountIp: {},
        interfacePortrait: {}

      }
    },
    methods: {
      traceabilityTask() {
        // console.log('===> ',this.id)
        let jobReportId = this.id
        traceReport({ jobReportId: jobReportId }).then((res) => {
          console.log(res)
          //顶部数据
          if (res.data.apiTraceCount) {
            this.kpi_1.value = res.data.apiTraceCount.traceDataCount
            this.kpi_2.value = res.data.apiTraceCount.upFlow
            this.kpi_3.value = res.data.apiTraceCount.downFlow
            this.kpi_4.value = res.data.apiTraceCount.senstiveDataCount
          }
          //近7天访问量趋势
          if (res.data.apiVisitTerms) {
            this.columnOption3.source = res.data.apiVisitTerms.reduce((r, c) => {
              r.push({
                'name': parseTime(c.name, '{y}-{m}-{d}'),
                'value': c.value
              })
              return r
            }, [])
          } else {
            this.columnOption3.source = []
          }
          //风险因子溯源分析
          if (res.data.apiRiskFactors) {
            this.columnOption2 = res.data.apiRiskFactors
          }
          //近7天命中接口
          if (res.data.apiTargetUrls) {
            this.columnOption4.source = res.data.apiTargetUrls.reduce((r, c) => {
              r.push({
                'name': c.name,
                'value': c.value
              })
              return r
            }, [])
          } else {
            this.columnOption4.source = []
          }
          //事件明细
          if (res.data.apiEventDetails) {
            this.eventDetails = res.data.apiEventDetails
          }
          // 账号IP画像 接口画像
          if (res.data.apiAddressPortrait) {
            this.accountIp = res.data.apiAddressPortrait
          }
          //接口画像
          if (res.data.apiPicPortrait) {
            this.interfacePortrait = res.data.apiPicPortrait
          }
          if (res.data.apiTracePaths) {
            let lineData = res.data.apiTracePaths.links
            lineData.push({
              source: null,
              target: '0',
              label: null
            })
            let data = this.listToTree(lineData, 'target', 'source')

            let firstData = [],
              secondData = [],
              thirdData = []
            data.forEach(f => {
              if (f.children && f.children.length) {
                f.children.forEach((s, index) => {
                  if (s.children && s.children.length) {
                    s.children.forEach((t, i) => {
                      thirdData.push({
                        source: t.source,
                        target: t.target,
                        apiUrl: t.name
                      })
                    })
                  }
                  secondData.push({
                    source: s.source,
                    target: s.target,
                    apiUrl: s.name
                  })
                })
                firstData.push({
                  source: f.source,
                  target: f.target,
                  apiUrl: f.name
                })
              }
            })

            thirdData.forEach((f, i) => {
              f.top = (i + 1) * 44
              f.left = 1200
            })

            secondData.forEach(f => {
              let total = 0
              thirdData.forEach(t => {
                if (f.target === t.source) {
                  total += t.top
                }
              })
              f.top = total / (f.children && f.children.length ? f.children.length : 1)
              f.left = 400
            })

            firstData[0].top = (secondData[secondData.length - 1].top + 44) / 2
            firstData[0].left = 30
            let nodeData = res.data.apiTracePaths.nodes.reduce((r, c) => {
              c.label = c.name
              c.position = {
                top: 0,
                left: 100
              }
              if (firstData.find(f => f.target === c.id)) {
                c.position.top = firstData.find(f => f.target === c.id).top
                c.position.left = firstData.find(f => f.target === c.id).left
                c.anchors = ['Right']
              }
              if (secondData.find(s => s.target === c.id)) {
                c.position.top = secondData.find(s => s.target === c.id).top
                c.position.left = secondData.find(s => s.target === c.id).left
                c.anchors = ['Left', 'Right']
              }
              if (thirdData.find(t => t.target === c.id)) {
                c.position.top = thirdData.find(t => t.target === c.id).top
                c.position.left = thirdData.find(t => t.target === c.id).left
                c.anchors = ['Left']
              }
              r.push(c)
              return r
            }, [])

            let line = res.data.apiTracePaths.links.reduce((r, c) => {
              r.push({
                left: c.source,
                right: c.target
              })
              return r
            }, [])

            let formData = {
              lineData: line,
              nodeData: nodeData
            }
            this.formData = JSON.stringify(formData)

            let applicationName

            let id = secondData.length && secondData[0].target ? secondData[0].target : ''

              if(id) {

                console.log(nodeData)
                let url = nodeData.find(f => f.id === id).label

                if(url) {
                  applicationName = url.split(':')[1].replace("\/\/", "")
                }

              }

            let protocolName = this.data.protocolName ? this.data.protocolName : ''

            this.title = '查看报告（ 应用名称：' + applicationName + '，协议：' + protocolName + '）'
          }
        })
      },
      listToTree(list, id, parentId) {
        let tree = []
        tree = list.filter(
          item1 =>
            !list.find((item2, index) => {
              // 如果有父节点
              if (item1[parentId] === item2[id]) {
                // 放进它父节点的children数组中；如果children不存在，初始化为空数组
                list[index].children = list[index].children || []
                list[index].children.push(item1)
              }
              // find返回第一个符合条件的元素，找到后，剩余的元素不再判断
              return item1[parentId] === item2[id]
            })
        )
        return tree
      },
      goBack() {
        this.$emit('traceabilityTaskView')
      },
      pieClick(e) {
        console.log(e)
        this.logquery = e.name
        this.openReport = true
      },
      traceabilityTaskReport() {
        this.openReport = false
      }

    },
    mounted() {
      this.traceabilityTask()
    },
    created() {
      // this.formData = JSON.stringify(this.formData)
    }
  }
</script>

<style scoped lang="scss">

  .execution-history-overview-wrap {
    width: 100%;
    height: 100%;
    overflow-x: hidden;
    overflow-y: scroll;

    .grid-column-4 {
      display: grid;
      grid-column-gap: 12px;
      grid-template-columns: 1fr 1fr 1fr 1fr;
    }

    .grid-column-2 {
      display: grid;
      grid-column-gap: 12px;
      grid-template-columns: 1fr 1fr;
    }

    .chart-container {
      height: 400px;
      background-color: #fff;
      box-shadow: rgba(0, 0, 0, 0.1) 0 2px 12px 0;
      border-radius: 4px;
      overflow: hidden;
    }

    .chart-container1 {
      height: 45px;
      background-color: #fff;
      box-shadow: rgba(0, 0, 0, 0.1) 0 2px 12px 0;
      border-radius: 4px;
      margin-top: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .report {
        margin-left: 15px;
      }

      .button {
        margin-right: 12px;
      }
    }

    .column-divided {
      height: 12px;
      width: 100%;
    }
  ::v-deep .title-card-content{
    .chart-table {
      height: 100%;
      .el-table{
        margin-top: 0;
      }
    }
  }


  }
</style>
